<?php 
/**
 * 用户管理中心
 * @author Nonant
 *
 */

class AccountAction extends BaseAction{
    
	function _initialize(){
    	parent::_initialize();
    }
    //用户个人首页
	//需要做的处理有：	1.当前订单状态。
	//					2.个人信息是否完善
	//					3.待定....
	public function index(){
    	//$this->display();
    	$this->profile();
    	exit;
	}
	
	public function sendList(){
		$this->display();
	}
	
	public function ajxSendList(){
		$this->display('send_list_box');
	}
	
    public function profile(){
    	$userInfo = M('User')->where('id='.$this->mid)->find();
    	//$agent = $_SESSION['userInfo']['agent'];
    	$agent = M('Agent')->where('user_id='.$this->mid)->find();
		$_SESSION['userInfo']['agent'] = $agent;
    	$agentstatus = $this->isAgentActive();
		
		$this->assign('agentstatus', $agentstatus);
    	$this->assign('userInfo', $userInfo);
    	$this->assign('agentInfo', $agent);
		$this->display('profile');
	}
	
/** 订单详情，并包含支付界面（未支付的订单） **/
	function ajxDetail(){
		$order_id	=	$_REQUEST['order_id'];
		$this->assign('order_id'		, $order_id);
		$this->display('detail_box');
	}
	
	public function rebatepay(){
		$this->display();
	}
	
	/**
	 * 显示插件设置页面
	 */
	public function pluginsetup(){
		$this->display();
	}
	
	/**
	 * 获得插件连接请求路径
	 */
	public function getpluginurl(){
		$agent = $_SESSION['userInfo']['agent'];
    	$agentstatus = $this->isAgentActive();
		if($agentstatus['status']!=1){
			exit(json_encode(array('status'=>'0','msg'=>$result['msg'])));
		}
		
		if(empty($agent['key'])){
			exit(json_encode(array('status'=>'0','msg'=>'请点击生成密钥！')));
		}
		
		//plugin/index.php/gift/index/p_uid/1004/p_key/11111111/p_fnc/-/p_par/-
		//以下参数不能为空，数组中如果有空值，需设置一个默认值。
		$param = array(	 'p_uid'=>$agent['user_id']		//联盟会员ID
						,'p_key'=>$agent['key']			//对应的密钥
						,'p_ver'=>'1.0'					//对应版本
						,'p_fnc'=>'-'					//对应的插件功能   暂时应该没有用到
						,'p_par'=>'-'					//附加参数,JSON格式
					   );
		//json U('plugin://gift/index',$param);
		exit(json_encode(array('status'=>'1','data'=>SITE_URL.U('plugin://index/index',$param),'dialog'=>SITE_URL.U('plugin://index/dialog',$param),'msg'=>'')));
	}
	
	/**
	 * 重新生成密钥
	 */
	public function recreatekey(){
		$agent = $_SESSION['userInfo']['agent'];
    	$agentstatus = $this->isAgentActive();
		if($agentstatus['status']!=1){
			exit(json_encode(array('status'=>'0','msg'=>$agentstatus['msg'].'12')));
		}
		
		include_once( QUICK_ADDONE_PATH.'/libs/String.class.php' );
        $randval = String::rand_string(6);
        //echo $randval;
        $key= md5($randval);
        //echo $randval.'='.$key."<br>";
        $map['key']	  	= $key;
		$no = M('Agent')->where(array('user_id'=>$this->mid))->save($map);
		
		if (!$no)exit(json_encode(array('status'=>'0','msg'=>'生成连接密钥失败！')));
		$agent = M('Agent')->where('user_id='.$this->mid)->find();
		$_SESSION['userInfo']['agent'] = $agent;
        exit(json_encode(array('status'=>'1','msg'=>'生成连接密钥成功！')));
	}
		
	/**
	 * 保存个人信息
	 */
	public function saveProfile(){
		$result = $this->isAgentActive();
		if($result['status']==1)$this->error('申请已通过不能修改');
		//参数合法性检查
		$required_field = array(
			'title'			=> '网站名称',
			'site_url'		=> '网站网址',
			'contact'		=> '联系人名',
			'phone'			=> '联系电话',
			'bank_name'		=> '开户银行',
			'bank_user'		=> '开户人名',
			'bank_no'		=> '汇款账户'
		);
		foreach ($required_field as $k => $v) {
			if ( empty($_POST[$k]) ) $this->error($v . '不可为空');
		}

		$map['site_url']	    = t($_POST['site_url']);
		$res = M('Agent')->where(" site_url='".$map['site_url']."' and enable='Y' and is_delete!='Y' and id!=".$this->mid)->count();
		if ( !$res ) {
		}else {
			$this->error('昵称已经被使用，请重新输入');
		}

		$map['title']		= t($_POST['title']);
		$map['site_url']	= t($_POST['site_url']);
		$map['contact']	  	= t($_POST['contact']);
		$map['phone']	  	= t($_POST['phone']);
		$map['bank_name'] 	= t($_POST['bank_name']);
		$map['bank_user'] 	= t($_POST['bank_user']);
		$map['bank_no'] 	= t($_POST['bank_no']);
		$map['user_id']	    = $this->mid;
		$map['sortcode']	= 'at_site';
		$map['enable']		= 'N';
		
		$dao = M('Agent');
		if($result['status']==0){
			$map['ctime']	  	= time();
			$no = $dao->add($map);
		}
		if($result['status']==-1){
			$map['mtime']	  	= time();
			$no = $dao->where(array('user_id'=>$this->mid,'enable'=>'N'))->save($map);
		}
		
		if (!$no) $this->error('申请失败，请重新操作！');
		$agent = M('Agent')->where('user_id='.$this->mid)->find();
		$_SESSION['userInfo']['agent'] = $agent;
		$this->success('申请成功，请等待结果！');
	}
    
	
	
	//修改密码
    public function doModifyPassword() {
	    if( strlen($_POST['password']) < 6 || strlen($_POST['password']) > 16 || $_POST['password'] != $_POST['repassword'] ) {
			//$this->error('密码必须为6-16位，且两次必须相同');
			exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'密码必须为6-16位，且两次必须相同'.$_POST['password'].'|'.$_POST['repassword'])));
		}
		if ($_POST['password'] == $_POST['oldpassword']) {
			exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'原始密码和新密码不应该相同')));
			//$this->error('原始密码和新密码不应该相同');
		}
		
    	$dao = M('user');
		$_POST['oldpassword'] = md5($_POST['oldpassword']);
		$map['id']			  = $this->mid;
		$map['password']	  = $_POST['oldpassword'];
	    if ( $dao->where($map)->find() ) {
	    	$_POST['password']    = md5($_POST['password']);
			if ( $dao->where($map)->setField('password', $_POST['password']) ) {
				exit(json_encode(array('status'=>'1','title'=>'','msg'=>'保存成功')));
				//$this->success('保存成功');
			}else {
				exit(json_encode(array('status'=>'0','title'=>'','msg'=>'抱歉：保存失败')));
				//$this->error('抱歉：保存失败');
			}
	    }else {
	    	exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'原始密码错误')));
			//$this->error('原始密码错误');
	   	}
    }
    
    //修改当前用户邮箱地址
    public function modifyEmail() {
	    $_POST['email']    = t($_POST['email']);
	    $_POST['oldemail'] = t($_POST['oldemail']);
	   	if ( !isValidEmail($_POST['email']) || !isValidEmail($_POST['oldemail']) ) {
	   		exit(json_encode(array('status'=>'-1','title'=>'','msg'=>'Email格式错误')));
	   		//echo -1;
	   		return ; //$this->error('Email格式错误');
	    }
	   	$map['id']			= $this->mid;
	   	$map['email']		= $_POST['oldemail'];
	   	if ( ! M('User')->where($map)->find() ) {
	    	exit(json_encode(array('status'=>'-2','title'=>'','msg'=>'原始Email错误')));
	    	//echo -2;
	    	return ; //原始Email错误
	    }
	   	if ( ! Model('User')->isEmailAvailable($_POST['email']) ) {
	    	exit(json_encode(array('status'=>'-3','title'=>'','msg'=>'新Emai已存在')));
	    	//echo -3;
	    	return ; //$this->error('新Emai已存在');
	    }
	    	
	   	//$opt_email_activate = model('Xdata')->lget('register');
	    	
	   	// 不需要验证邮件时, 直接修改帐号
	   	/**
		if (!$opt_email_activate['register_email_activate']) {
			if ( M('user')->where($map)->setField('email', $_POST['email']) ) {
				service('Passport')->logoutLocal();
				$json_str=json_encode(array('status'=>'1','title'=>'','msg'=>'保存成功, 请重新登陆'));
	    		//echo 1;
			}else {
				$json_str=json_encode(array('status'=>'0','title'=>'','msg'=>'保存失败'));
	    		//echo 0;
			}
			unset($opt_email_activate);
			exit($json_str);
		}
		**/	
		//unset($opt_email_activate);
				
		// 邮件验证
	    //添加验证
	    $data = array('oldemail'=>$_POST['oldemail'], 'email'=>$_POST['email']);
	    if ( $url = service('Validation')->addValidation($this->mid, '', 'Index://Public/doModifyEmail', 'modify_account', serialize($data)) ) {
	    	// 发送验证邮件
	    	global $ts;
    		$body = <<<EOD
<strong>{$ts['user']['uname']}，你好：</strong><br/>
				
您只需通过点击下面的链接重置您的帐号：<br/>
				
<a href="$url">$url</a><br/>
				
如果通过点击以上链接无法访问，请将该网址复制并粘贴至新的浏览器窗口中。<br/>
				
如果你错误地收到了此电子邮件，你无需执行任何操作来取消帐号！此帐号将不会启动。
EOD;
			
			if (service('Mail')->send_email($_POST['email'], "重置{$ts['site']['site_name']}帐号", $body)) {
				$json_str=json_encode(array('status'=>'1','title'=>'','msg'=>'激活邮件已发送，请通过邮件激活本次修改'));
	   			//echo '2';
			}else {
				$json_str=json_encode(array('status'=>'-4','title'=>'','msg'=>'验证邮件发送失败'));
	   			//echo '-4';
			}
			
    	}else {
    		$json_str=json_encode(array('status'=>'0','title'=>'','msg'=>'保存失败'));
	    			//echo '0';
    	}
    	exit($json_str);
    }


	//头像处理
    function avatar(){
        $type = $_REQUEST['t'];
        $pAvatar = D('Avatar');
        $pAvatar ->uid = $this->mid;
        if( $type == 'upload' ){
            echo $pAvatar->upload();
        }elseif ( $type == 'save'){
            $pAvatar->dosave($this->mid);
        }elseif ( $type == 'camera'){
            $pAvatar->getcamera();
        }else{
        	$this->display();
        }
    }
    
    
    /**
     * 现金账户。
     */
    function cash(){
    	exit;
    	$uamount = service('UserAccount')->get4User();
    	$this->assign('totalamount', $uamount['current_money']);
    	$this->display();
    }
    
    function ajxRefreshCash(){
    	exit;
    	$uaccount = service('UserAccount')->refresh4UserCash();
    	$uaccount['current_money_format'] = formatMoney($uaccount['current_money']);
    	$uaccount['used_money_format'] = formatMoney($uaccount['used_money']);
    	exit( json_encode(array('status'=>'1','data'=>$uaccount)) );
    }
    
 	/**
     * 用户现金。分页查询时调用。
     */
    function ajxCash(){
  		exit;
    	$this->display('cash_list_box');
    }
    
}
?>